﻿using Common.Common;
using DataCenter;
using DcpServer.Domain;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using WSDTO;

namespace DBLibrary
{
    public class PatientRepository
    {
        public bool AddPatient(Patient patient)
        {
            if(patient == null)
            {
                return true;
            }
            try
            {
                using(TransactionScope transaction = new TransactionScope())
                {
                    using(var db = new AppDbContext())
                    {
                        db.Patient.Add(patient);
                        //MainDataTable mainDataTable = new MainDataTable()
                        //{
                        //    Id = Guid.NewGuid(),
                        //    PatientId = patient.Id,
                        //    Flag = 0,
                        //};
                        //db.MainDataTable.Add(mainDataTable);
                        db.SaveChanges();
                    }
                    transaction.Complete();
                }
                LogHelper.Info("添加病人成功");
            }catch(Exception e)
            {
                LogHelper.Error("病人ID:" + patient.Id + ",错误信息:" + e.Message);
            }
            return true;
        }
        
        public static Patient SelectPatient(Guid id)
        {
            using (var db = new AppDbContext())
            {
                try
                {
                    Patient patient = db.Patient.Where((a => a.Id == id)).FirstOrDefault();
                    return patient;
                }
                catch(Exception e)
                {
                    Console.WriteLine("异常" + e.Message);
                    return null;
                }
                
               
            }
        }

        public void AddValueData(ValueData valueData, Guid patientId)
        {
            try
            {
                // 查询表之中是否存在记录
                using (var db = new AppDbContext())
                {
                    byte[] tempBytes;
                    if(valueData.Temp == null)
                    {
                        tempBytes = new byte[0];
                    }
                    else
                    {
                        tempBytes = CommonMethod.Instance.StructToBytes(valueData.Temp);
                    }
                    MainDataTable dataTable = db.MainDataTable.Where(a => a.PatientId == patientId && a.Flag == 0).DefaultIfEmpty(null).First();
                    if (dataTable == null)
                    {
                        MainDataTable mainDataTable = new MainDataTable()
                        {
                            Id = Guid.NewGuid(),
                            PatientId = patientId,
                            StartTime = valueData.CreateTime,
                            Hr = new byte[] { (byte)valueData.Hr },
                            Spo2 = new byte[] { (byte)valueData.Spo2 },
                            Resp = new byte[] { (byte)valueData.Resp },
                            Temp =  tempBytes,
                            Power = new byte[] { (byte)valueData.Power },
                            Flag = 0,
                        };
                        db.MainDataTable.Add(mainDataTable);
                    }
                    else  // 追加数据
                    {
                        dataTable.Hr = (dataTable.Hr ?? Array.Empty<byte>()).Concat(new byte[] { (byte)valueData.Hr }).ToArray();
                        dataTable.Spo2 = (dataTable.Spo2 ?? Array.Empty<byte>()).Concat(new byte[] { (byte)valueData.Spo2 }).ToArray();
                        dataTable.Resp = (dataTable.Resp ?? Array.Empty<byte>()).Concat(new byte[] { (byte)valueData.Resp }).ToArray();
                        dataTable.Power = (dataTable.Power ?? Array.Empty<byte>()).Concat(new byte[] { (byte)valueData.Power }).ToArray();
                        dataTable.Temp = (dataTable.Temp ?? Array.Empty<byte>()).Concat(tempBytes).ToArray();
                        dataTable.ModifiedTime = valueData.CreateTime;
                    }
                    db.SaveChanges();

                }
            }catch(Exception e)
            {
                LogHelper.Error("AddValueData:" + e.Message);
            }
        }

        public List<NIBPDTO> GetNibpReviews(Guid id)
        {
            MainDataTable dataTable = GetMainDataTables(id, 0);
            if (dataTable.NIBP == null)
                return new List<NIBPDTO>();
            try
            {
                List<NIBPDTO> nIBPDTOs = CommonMethod.Instance.BytesToStruct<NIBPDTO>(dataTable.NIBP);
                return nIBPDTOs;
            }
            catch(Exception e)
            {
                LogHelper.Info(e.Message);
                return new List<NIBPDTO>();
            }    
        }


        public void UpdateMainDataTableNIBP(NibpReview nibp, Guid patientId)
        {
            using (var db = new AppDbContext())
            {
                /*MainDataTable data1 = db.MainDataTable.Where(a => a.PatientId == patientId && a.Flag == 0).FirstOrDefault();
                if (data1 == null)
                {
                    MainDataTable mainDataTable = new MainDataTable()
                    {
                        Id = Guid.NewGuid(),
                        PatientId = patientId,
                        Flag = 0,
                    };
                    db.MainDataTable.Add(mainDataTable);
                    db.SaveChanges();
                }*/
                MainDataTable data = db.MainDataTable.Where(a => a.PatientId == patientId && a.Flag == 0).FirstOrDefault();

                NIBPDTO nIBPDTO = new NIBPDTO()
                {
                    t = CommonHelper.GetTimeStamp(nibp.CreateTime),
                    nd = (int)nibp.Nd,
                    ns = (int)nibp.Ns,
                    nm = (int)nibp.Nm
                };
                try
                {
                    byte[] dataArray = CommonMethod.Instance.StructToBytes(nIBPDTO);
                    data.NIBP = data.NIBP == null ? dataArray : data.NIBP.Concat(dataArray).ToArray();
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    LogHelper.Info(e.Message);
                }
            }
        }

        public MainDataTable GetMainDataTables(Guid PatientId, int flag)
        {
            using (var db = new AppDbContext())
            {
                return db.MainDataTable.Where(o => o.PatientId.Equals(PatientId) && (o.Flag.Equals(flag))).FirstOrDefault();
            }
        }

        public void Archive(Guid patientId)
        {
            using (var db = new AppDbContext())
            {
                MainDataTable dataTable = GetMainDataTables(patientId, 0);
                dataTable.Flag = 1;
                db.SaveChanges();
            }
        }

        public NibpReview getLastNibpReview(Guid patientID)
        {
            try
            {
                NIBPDTO nIBPDTO = GetNibpReviews(patientID).FirstOrDefault();
                NibpReview review = new NibpReview()
                {
                    SerialNo = 0,
                    Nd = nIBPDTO.nd,
                    Ns = nIBPDTO.ns,
                    Nm = nIBPDTO.nm,
                };
                return review;
            }catch(Exception e)
            {
                return null;
            }
            
        }
    }


}
